package com.example.combwx.mvp.view.uesr;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.BarUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.example.combwx.App;
import com.example.combwx.R;
import com.example.combwx.db.UserUtility;
import com.example.combwx.mvp.base.model.BaseEntity;
import com.example.combwx.mvp.base.presenter.IPresenter;
import com.example.combwx.mvp.base.view.BaseFragment;
import com.example.combwx.mvp.contract.UserContract;
import com.example.combwx.mvp.di.DaggerUserComponent;
import com.example.combwx.mvp.di.UserModels;
import com.example.combwx.mvp.model.HttpCode;
import com.example.combwx.mvp.model.entity.ResponseUserEntity;
import com.example.combwx.mvp.model.entity.UserEntity;
import com.example.combwx.mvp.model.entity.UserItemEntity;
import com.example.combwx.mvp.model.entity.UserMenuEntity;
import com.example.combwx.mvp.presenter.UserPresenter;
import com.example.combwx.mvp.view.ChangeinformationActivity;
import com.example.combwx.mvp.view.RegisterActivity;
import com.example.combwx.mvp.view.uesr.adapter.UserAdapter;
import com.example.combwx.mvp.view.uesr.adapter.UserMenuAdapter;
import com.example.combwx.network.Api;
import com.example.combwx.network.LoadImage;
import com.example.combwx.test.di.DaggerTestComponent;
import com.example.combwx.utils.LogUtils;
import com.example.combwx.utils.SpUtils;
import com.example.combwx.widget.x5.X5WebView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

public class UserFragment extends BaseFragment<UserPresenter>
        implements UserContract.IUserView, OnItemChildClickListener, View.OnClickListener {

    private static final String TAG = "UserFragment";
    private View menuView, timeLineVIew, timestamp;
    private RecyclerView menu_rv;
    private RecyclerView user_rv;
    private UserAdapter adapter;
    private UserMenuAdapter menuAdapter;
    private ImageView menuheadimg;
    private TextView usertext;
    private TextView tv_01;
    private InformationBroadcast informationBroadcast;
//    @Override
//    public View addStatusView() {
//        return f(R.id.user_linear);
//    }
//
//    @Override
//    public int addColor() {
//        return Color.RED;
//    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        informationBroadcast = new InformationBroadcast();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("nickname");
        getActivity().registerReceiver(informationBroadcast, intentFilter);
    }

    @Override
    public int bindLayout() {
        return R.layout.fragment_user;
    }

    @Override
    public void initView() {
        user_rv = f(R.id.user_rv);
        menuView = LayoutInflater.from(getContext()).inflate(R.layout.view_user_menu, null);
        timeLineVIew = LayoutInflater.from(getContext()).inflate(R.layout.view_user_speed, null);
        timestamp = LayoutInflater.from(getContext()).inflate(R.layout.item_times_tamp, null);
        menu_rv = menuView.findViewById(R.id.menu_rv);
        menuheadimg = menuView.findViewById(R.id.menu_head_img);
        usertext = menuView.findViewById(R.id.user_name);
        tv_01 = menuView.findViewById(R.id.user_name);

        EventBus.getDefault()
                .register(this);

//        InformationBroadcast informationBroadcast = new InformationBroadcast();
//        IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction("nickname");
//        getActivity().registerReceiver(informationBroadcast,intentFilter);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 4);
        gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
        menu_rv.setLayoutManager(gridLayoutManager);
        menuAdapter = new UserMenuAdapter();
        menu_rv.setAdapter(menuAdapter);
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        user_rv.setLayoutManager(manager);
        adapter = new UserAdapter();
        //添加头布局
        adapter.addHeaderView(menuView, 0);
        adapter.addHeaderView(timestamp, 1);
        adapter.addHeaderView(timeLineVIew, 2);
        adapter.setOnItemChildClickListener(this);
        user_rv.setAdapter(adapter);
        try {
            List<UserEntity> userEntities = UserUtility.getInstance().getDaoSession().loadAll(UserEntity.class);
            String user_name = userEntities.get(0).user_name;
            String user_img = userEntities.get(0).getUser_img();
            com.blankj.utilcode.util.LogUtils.json(user_img);
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_01.setText(user_name);
                    Log.i(TAG, "initView: " + tv_01);
                    Glide.with(getContext()).load(user_img)
                            .transform(new CircleCrop(), new CenterCrop())
                            .into(menuheadimg);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }

        tv_01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Boolean user = SpUtils.accounFatch();
                Log.i(TAG, "onClick: " + user.toString());
                if (user == true) {
                    startPage(ChangeinformationActivity.class);
                } else {
                    startPage(RegisterActivity.class);
                }
            }
        });

    }

    @Override
    public void initData() {
        p.initData();
        List<UserEntity> list = null;
        try {
            list = UserUtility.getInstance().getDaoSession().queryBuilder(UserEntity.class).list();
            if (list != null) {
                if (list.size() > 0) {
                    UserEntity entity = list.get(0);
                    refreshUser(entity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void inject() {
        DaggerUserComponent.builder()
                .userModels(new UserModels(this))
                .build().inject(this);
    }

    @Override
    public void refresh(BaseEntity entity) {

    }

    @Override
    public void refreshMenu(List<UserMenuEntity> menues) {
        menuAdapter.setNewInstance(menues);
    }

    @Override
    public void refreshItemes(List<UserItemEntity> itemes) {
        adapter.setNewInstance(itemes);
    }

    @Override
    public void showUser(BaseEntity baseEntity) {
        ResponseUserEntity responseUserEntity = (ResponseUserEntity) baseEntity;
        Log.i(TAG, "showUser: "+baseEntity.toString());
        String user_img = responseUserEntity.getValues().getUser_img();
        com.blankj.utilcode.util.LogUtils.json(responseUserEntity.getValues().getUser_img());

        Glide.with(getActivity()).load(Api.FileUrl+responseUserEntity.getValues().getUser_img())
                .transform(new CenterCrop(), new CircleCrop()).into(menuheadimg);
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void even(String s) {
        if (s != null) {
            try {
                List<UserEntity> userEntities = UserUtility.getInstance().getDaoSession().loadAll(UserEntity.class);
                String user_name = userEntities.get(0).user_name;
                String user_img = userEntities.get(0).getUser_img();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_01.setText(user_name);
                        Glide.with(getContext()).load(user_img)
                                .transform(new CircleCrop(), new CenterCrop())
                                .into(menuheadimg);
                        Log.i(TAG, "initView: " + tv_01);
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void refreshUserData(UserEntity userEntity) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                usertext.setText(userEntity.user_name);
            }
        });
        Log.i(TAG, "refreshUserData: "+"refreshUserData");
        p.selUser(userEntity.user_id, HttpCode.SELUSERCODE);

    }

    @Override
    public void onClick(View view) {
//        List<UserEntity> users = null;
//        try {
//            users = UserUtility.getInstance().getDaoSession().queryBuilder(UserEntity.class).list();
//            if (users==null) {
//                startPage(LoginActivity.class);
//                return;
//            }
//            if (users.size() == 0) {
//                startPage(LoginActivity.class);
//                return;
//            }
//            startPage(UserDetailsActivity.class);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        TextView viewById = view.findViewById(R.id.user_itemes_tv);
        viewById.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(), SetUserActivity.class);
                startActivity(intent);
            }
        });
    }

    class InformationBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().contains("nickname")) {
//                usertext.setText("" + intent.getStringExtra("a"));
                UserEntity userEntity = intent.getParcelableExtra("userValues");
                refreshUserData(userEntity);
            }
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(informationBroadcast);
        EventBus.getDefault().unregister(this);
    }

    private void refreshUser(UserEntity entity) {
        LogUtils.show("entity" + (entity == null));
        LoadImage.loadCircleImg(entity.user_img, menuheadimg);
        usertext.setText(entity.user_name + "Lv" + entity.user_integral);
    }
}
